extends CharacterBody2D

@onready var timer: Timer = $Timer
const BULLET = preload("res://bullet/bullet.tscn")
@onready var bullet_pos = $bullet_pos
const bullet_speed:int = 1000
var target_pos:Vector2 = Vector2.ZERO
var enemys:Array = []

func shoot():
	if enemys.size()<=0:
		return
	var bullet = BULLET.instantiate()
	bullet.global_position = bullet_pos.global_position
	bullet.target_pos = global_position.direction_to(enemys[0].global_position)
	bullet.SPEED = bullet_speed
	get_tree().root.add_child(bullet)
	timer.start()
	
func sort_enemys():
	if enemys.size()>0:
		enemys.sort_custom(func(a,b):
			return a.global_position.direction_to(global_position) >= b.global_position.direction_to(global_position)
		)
		
func _on_enemy_area_body_entered(body: Node2D) -> void:
	if not enemys.has(body):
		enemys.append(body)
		sort_enemys()
	target_pos = body.global_position
	look_at(body.position)
	shoot()
	pass # Replace with function body.


func _on_enemy_area_body_exited(body: Node2D) -> void:
	rotation_degrees = 0
	enemys.erase(body)
	pass # Replace with function body.


func _on_timer_timeout() -> void:
	shoot()
	timer.start()
	pass # Replace with function body.
